﻿using Aker.DevTeam;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Microsoft.Win32;
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace Aker
{
    public partial class Login : XPopupForm
    {
        public bool IsOnline
        {
            get { return cmbFuar.SelectedIndex == 0; }
        }

        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {
            DirectoryInfo di = new DirectoryInfo("c:\\Aker");
            if (!di.Exists)
                di.Create();
            FileInfo fi = new FileInfo("c:\\Aker\\Aker.txt");

            if (!fi.Exists)
                fi.Create().Close();

            this.AcceptButton = btnLogin;
            this.KeyPreview = true;
            this.Shown += new EventHandler(Login_Shown);
            this.KeyDown += new KeyEventHandler(Login_KeyDown);

            if (Environment.MachineName.ToUpper() == "KGULCAN")
            {
                txtUsername.Text = "tester";
                txtPassword.Text = "1";
                cmbFuar.SelectedIndex = 0;
                cmbTest.SelectedIndex = 1;
                //btnLogin.PerformClick();
            }


            AppSession.IsOnline = IsOnline;
            AppSession.Language = cmbDil.EditValue.ToStringNN();



        }

        private void Login_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.F12)
            {
                XtraMessageBox.Show("OK");
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (CheckCredentials(txtUsername.Text, txtPassword.Text))
            {
                if (lblNewPassword.Visible)
                {
                    if (txtNewPassword.Text == "")
                    {
                        if (cmbDil.SelectedIndex == 0)
                            XtraMessageBox.Show("Yeni parola boş olamaz.");
                        else
                            XtraMessageBox.Show("New password can not be blank.");
                        return;
                    }
                    else if (txtNewPassword.Text.Length < 3)
                    {
                        if (cmbDil.SelectedIndex == 0)
                            XtraMessageBox.Show("Yeni parola en az 3 karakter olmalı.");
                        else
                            XtraMessageBox.Show("New password must be at least 3 characters.");
                        return;
                    }

                    Data.DM.ExecuteScalar("UpdKullanici", txtUsername.Text, txtNewPassword.Text);
                }

                this.DialogResult = DialogResult.OK;
            }
            else
            {
                if (cmbDil.SelectedIndex == 0)
                    XtraMessageBox.Show("Erişim yetkiniz yok!");
                else
                    XtraMessageBox.Show("Access denied!");

                txtPassword.Text = String.Empty;
                txtPassword.Focus();
            }
        }

        private void Login_Shown(object sender, EventArgs e)
        {
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
                this.Text += " - v" + System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();

            string userName = RememberUser();

            if (userName != String.Empty)
            {
                txtUsername.Text = userName;
                txtPassword.Focus();
            }
            else
                txtUsername.Focus();
        }

        private string RememberUser(string UserNameToSave = "")
        {
            try
            {
                RegistryKey register = Registry.CurrentUser.CreateSubKey(@"Software\Aker");
                if (UserNameToSave != "")
                {
                    register.SetValue("UserLastLoggedIn", UserNameToSave, RegistryValueKind.String);
                    Registry.LocalMachine.Flush();
                }
                else
                    UserNameToSave = (string)register.GetValue("UserLastLoggedIn", String.Empty);

            }
            catch (Exception)
            {
            }
            return UserNameToSave;
        }

        private void lnkChangePassword_OpenLink(object sender, OpenLinkEventArgs e)
        {
            bool visible = false;
            if (cmbDil.SelectedIndex == 0)
                visible = (btnChangePassword.Text == "Parola Değiştir");
            else
                visible = (btnChangePassword.Text == "Change Password");

            string toggle = "";

            if (visible)
            {
                if (cmbDil.SelectedIndex == 0)
                    toggle = "Parola Değiştirme";
                else
                    toggle = "Don't Change Password";
            }
            else
            {
                if (cmbDil.SelectedIndex == 0)
                    toggle = "Parola Değiştir";
                else
                    toggle = "Change Password";
            }

            btnChangePassword.Text = toggle;
            lblNewPassword.Visible = txtNewPassword.Visible = visible;
        }

        public bool CheckCredentials(string Username, string Password)
        {
            DataTable dtCredentials = null;
            AppSession.UserInfo = new User();
            AppSession.UserInfo.UserName = Username;
            AppSession.UserInfo.Password = Password; ;

            if (!IsOnline)
            {
                Data.Init(Data.LocalConnectionString);

                dtCredentials = Data.DM.ExecuteDataTable("GetKullanici", Username, Password);
                if (dtCredentials == null || dtCredentials.Rows.Count < 1)
                    return false;
            }
            else
            {
                Aker.ceGate.ceGateSoapClient gate = new ceGate.ceGateSoapClient();

                try
                {
                    dtCredentials = gate.GetAkerCredentials(Username, Password, "confexpert.karbel.com");
                }
                catch (Exception ex)
                {
                    if (cmbDil.SelectedIndex == 0)
                        XtraMessageBox.Show("Bağlantı kurulamıyor. Lütfen internet bağlantınızı kontrol edin ya da çevrımdışı bağlanın.");
                    else
                        XtraMessageBox.Show("Can not connect. Please check your internet connection or login as offline.");

                    Clipboard.SetText(ex.ToString());
                    return false;
                }

                if (dtCredentials == null)
                    return false;

                string connectionString = dtCredentials.Rows[0]["ConnectionString"].ToString();
                if (cmbTest.SelectedIndex == 1)
                {
                    connectionString = connectionString.Replace("Aker;", "AkerTest;");
                    AppSession.IsTest = true;
                }

                Data.Init(connectionString);
            }

            DataRow drUser = dtCredentials.Rows[0];

            AppSession.UserInfo.UserId = (int)drUser["KullaniciId"];
            AppSession.UserInfo.Yonetici = (bool)drUser["Yonetici"];
            AppSession.UserInfo.Name = drUser["AdSoyad"].ToString();
            AppSession.UserInfo.Email = drUser["ePosta"].ToString();
            AppSession.UserInfo.YetkiId = (int)drUser["YetkiId"];
            RememberUser(Username);

            return true;
        }

        private void cmbFuar_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbDil.SelectedIndex == 0)
                btnChangePassword.Text = "Parola Değiştir";
            else
                btnChangePassword.Text = "Change Password";

            lblNewPassword.Visible = txtNewPassword.Visible = false;
            btnChangePassword.Visible = IsOnline;
            AppSession.IsOnline = IsOnline;
        }

        private void cmbDil_EditValueChanged(object sender, EventArgs e)
        {
            AppSession.Language = cmbDil.EditValue.ToStringNN();

            if (cmbDil.SelectedIndex == 0)
            {
                labelControl1.Text = "Kullanıcı Adı";
                labelControl2.Text = "Parola";
                labelControl2.Location = new System.Drawing.Point(labelControl1.Location.X + 20, labelControl2.Location.Y);
                labelControl3.Text = "Lokasyon";
                lblNewPassword.Text = "Yeni Parola";
                btnChangePassword.Text = "Parola Değiştir";
                btnLogin.Text = "Giriş";

                int index = cmbFuar.SelectedIndex;
                cmbFuar.Properties.Items[0] = "Aker Merkez (Çevrimiçi)";
                cmbFuar.Properties.Items[1] = "Fuar (Çevrimdışı)";
                cmbFuar.SelectedIndex = index;

            }
            else
            {
                labelControl1.Text = "Username";
                labelControl2.Text = "Password";
                labelControl2.Location = new System.Drawing.Point(labelControl1.Location.X, labelControl2.Location.Y);
                labelControl3.Text = "Location";
                lblNewPassword.Text = "New Password";
                btnChangePassword.Text = "Change Password";
                btnLogin.Text = "Login";

                int index = cmbFuar.SelectedIndex;
                cmbFuar.Properties.Items[0] = "Aker Center (Online)";
                cmbFuar.Properties.Items[1] = "Fair (Offline)";
                cmbFuar.SelectedIndex = index;
            }
        }

        private void txtUsername_EditValueChanged(object sender, EventArgs e)
        {
            if (txtUsername.Text == "GK" || txtUsername.Text == "yasar.karabel" || txtUsername.Text == "necmi.demirel" || txtUsername.Text == "sargun.saltik" || txtUsername.Text == "tester" || txtUsername.Text == "ridvan.celepcikay")
            {
                cmbTest.Visible = true;
            }
            else
                cmbTest.Visible = false;
        }

    }
}